package com.xiongzai.lambda;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 测试性能(Java 8 的循环和Java 7 的循环耗时的对比测试)
 * <p>
 * 熊崽
 */
public class Performance {
    private static final Logger logger = LoggerFactory.getLogger(Performance.class);
    
    public static void main(String[] args) {
        List<String> list = getLoopList();
        /*百万级数据性能测试：
         * for each 执行耗时 : 3.933 秒
         * list.stream().forEach 执行耗时 : 3.933 秒
         * list.forEach 执行耗时 : 3.806 秒
         * list.parallelStream().forEach 执行耗时 : 6.898 秒
         * 个人感觉这样测试的结果不符合预期，应该是parallelStream的效率更高的，但是感觉cpu没有利用起来
         * */
        normalBeforeLoop(list);
        normalAfterLoop(list);
        notNormalAfterLoop(list);
    }
    
    private static void notNormalAfterLoop(List<String> list) {
        long a = System.currentTimeMillis();
        list.parallelStream().forEach(System.out::print);
        logger.info(new StringBuilder().append(" list.parallelStream().forEach 执行耗时 : ")
                .append((System.currentTimeMillis() - a) / 1000f).append(" 秒 ").toString());
    }
    
    private static void normalAfterLoop(List<String> list) {
        long a = System.currentTimeMillis();
        list.stream().forEach(System.out::print);
        logger.info(new StringBuilder().append(" list.stream().forEach 执行耗时 : ")
                .append((System.currentTimeMillis() - a) / 1000f).append(" 秒 ").toString());
        long a1 = System.currentTimeMillis();
        list.forEach(System.out::print);
        logger.info(new StringBuilder().append(" list.forEach 执行耗时 : ")
                .append((System.currentTimeMillis() - a1) / 1000f).append(" 秒 ").toString());
    }
    
    private static void normalBeforeLoop(List<String> list) {
        long a = System.currentTimeMillis();
        for (String s : list) {
            System.out.print(s);
        }
        logger.info(new StringBuilder().append(" for each 执行耗时 : ")
                .append((System.currentTimeMillis() - a) / 1000f).append(" 秒 ").toString());
    }
    
    private static List<String> getLoopList() {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 1000000; i++) {
            list.add("item " + i);
        }
        return list;
    }
}